<template>
  <div style="padding: 15px;">
    <vxe-toolbar>
      <template v-slot:buttons>
        <el-button @click="findInventoryList('search')">查询</el-button>
        <el-button type="primary" @click="funcSubmit">确定</el-button>
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      show-overflow
      keep-source
      height="700"
      align="center"
      row-id="code"
      class="mytable-footer"
      :loading="loading"
      auto-resize
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      :checkbox-config="{checkRowKeys: selectData, trigger: 'row', highlight: true, range: true, reserve: true }"
      :sort-config="{remote: true}"
      :scroll-y="{mode: 'wheel'}"
      @sort-change="sortList"
      @scroll="scrollEvent"
    >
      <vxe-table-column type="checkbox" width="60" fixed="left"></vxe-table-column>
      <vxe-table-column  >
        <vxe-table-column field="warehouseSpaceName" min-width="200" title="库区"  />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseSpaceCode" filterable placeholder="请选择库区" clearable>
            <el-option v-for="item in warehouseSpaceList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="locationName" min-width="200" title="库位"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.locationName" placeholder="请输入库位" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" min-width="200" title="入驻商"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shipmentName" placeholder="请输入入驻商名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodsName" min-width="200" title="商品名称"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodsName" placeholder="请输入商品名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodCode" title="商品编码" min-width="200"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodCode" placeholder="请输入商品编码" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodsBarCode" title="商品条码" min-width="200"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodsBarCode" placeholder="请输入商品条码" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="canUseQuantity" title="可用库存数量" min-width="180" :formatter="formatterCanUseQuantity" />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input v-model="listQuery.canUseQuantityFloor" placeholder="下限" ref="canUseQuantity" type='number' style="width:45%;" />
            &nbsp;-&nbsp;
            <el-input v-model="listQuery.canUseQuantityCeiling" placeholder="上限" type='number' style="width:45%;" />
          </el-row>
        </template>
      </vxe-table-column>

      <vxe-table-column field="moveQuantity" title="移出数量" min-width="200"  :edit-render="{name: '$input',}"/>
       <vxe-table-column>
        <vxe-table-column
          field="gmtManufacture"
          title="生产日期"
          min-width="360"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtManufacture"
            type="daterange"
            value-format="yyyy-MM-dd"
            style="width:100%"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtManufacture')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtExpire"
          title="过期日期"
          min-width="360"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtExpire"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"

            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtExpire')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtStock"
          title="存货日期"
          min-width="360"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtStock"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtStock')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="receiveLot" title="入库批次" min-width="200"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.receiveLot" placeholder="请输入入库批次" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="goodsStatusName" title="库存状态" min-width="200"  />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodsStatusName" placeholder="请输入库存状态" clearable />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="isLock" title="锁定状态" min-width="200" :formatter="formatterIsLock" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.isLock" filterable placeholder="请选择" clearable>
            <el-option value="0" label="否" />
            <el-option value="1" label="是" />
          </el-select>
        </template>
      </vxe-table-column>

    </vxe-table>
  </div>
</template>
<script>
import { getWarehouseSpace, getLocation } from "@/api/basicInfo";
import { inventoryCanUse } from "@/api/store";

export default {
  name: 'MoveChooseInventory',
  props: {
    warehouseCode: {
      type: String,
      required: true
    },
    selectData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      tableData: [],
      loading: false,
      listQuery: {
        total: 0, //总数
        warehouseCode: "",
        warehouseSpaceCode: "",
        location: "",
        goodsName: "",
        goodsStatus: "",
        goodsBarCode: "",
        pageNum: 1,
        pageSize: 50,
        locationName:'',
        sortField: "",
        sortType: "",
        receiveLot: "",
      },
      warehouseSpaceList: [],
      locationList: [],
      // 所有勾选的数据
      checkedRecordsMap: new Map(),
      oldRecordsMap: new Map(),
      resultMap:{
        addRecordsMap: new Map(),
        removeRecordsMap: new Map(),
      },
      noMoreData: false, // 数据是否全部加载完成
      // one:true,
      // two:true,
      // three:true
      // 日期选项
      gmtExpire: "", //过期日期 ,
      gmtManufacture: "", //生产日期 ,
      gmtStock: "", //存货日期 ,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },

  created() {
    this.getInfo(this.warehouseCode)
    this.findInventoryList()
  },
  mounted () {
    window.addEventListener('keydown', event => {
      // console.log('按下' + event.key)
      if (event.keyCode === 9) {
        event.preventDefault()
      }
    })
  },
 destroyed () {
    window.removeEventListener('keydown', event => {
      event.preventDefault()
    })
  },
  methods: {
    inputBlur(row){
      let moveQuantity = Number(row.row.moveQuantity)
      if(!moveQuantity||moveQuantity<0){
        this.$message.error('请输入大于0的数')
        this.one = false
        return
      }
      this.one = true
      let reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/
      if(!reg.test(moveQuantity)){
        this.$message.error('小数点后保留六位小数，不能为负')
        this.two =false
        return
      }
      this.two = true
      let canUseQuantity = Math.round((Number(row.row.quantity)-Number(row.row.useQuantity))*1000)/1000
      if(moveQuantity>canUseQuantity){
        this.$message.error('移出数量不能大于可用数量')
        this.three = false
        return
      }
      this.three = true
    },
      scrollEvent(e) {
        if (e.isY && !this.noMoreData) {
            // 函数防抖
            if (this.timer) {
              clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
              const el = this.$refs.xTable.$el.querySelector('.vxe-table--body-wrapper')
              const num = el.scrollHeight - (el.offsetHeight + el.scrollTop)
              if (num === 0 || num < 100) {
                this.listQuery.pageNum = this.listQuery.pageNum+1
                // const rowNum = this.listQuery.pageNum * this.listQuery.pageSize
                this.findInventoryList()
              }
            }, 500)
        }
      },
    // 初始化移位单code
    getInfo(warehouseCode, initRecords) {
      this.checkedRecordsMap = new Map();
      this.oldRecordsMap = new Map();
      this.resultMap.addRecordsMap = new Map();
      this.resultMap.removeRecordsMap = new Map();

      this.listQuery.warehouseCode = warehouseCode;
      this.findWarehouseSpaceList();
      // this.initCheckedRecordsMap(initRecords);
    },

    // 根据仓库查询可用库存
    findInventoryList(rowNum){
      this.loading = true;
      if (rowNum === 'search') {
        this.listQuery.pageNum = 1
      }
      inventoryCanUse(this.listQuery).then((response)=>{
        if (rowNum === 'search') {
          this.tableData = response.data.records
        } else {
          this.tableData = this.tableData.concat(response.data.records)
        }
        this.listQuery.total = response.data.total;
        for(let i = 0 ; i<this.tableData.length; i++){
          // 增加冗余字段，由于新增、修改时对应字段名不一致，有些字段需要多个名称
          this.tableData[i].inventoryCode = this.tableData[i].code;
          this.tableData[i].goodsUnitName = this.tableData[i].unitName;
          this.tableData[i].spaceName = this.tableData[i].warehouseSpaceName;
          this.tableData[i].num = this.tableData[i].quantity - this.tableData[i].useQuantity;
          if(this.checkedRecordsMap.has(this.tableData[i].inventoryCode)){
            this.$refs.xTable.setCheckboxRow(this.tableData[i], true);
          }
        }
        this.loading = false;
        if (response.data.records.length === 0 || response.data.total <= this.tableData.length) {
          this.noMoreData = true
        } else {
          this.noMoreData = false
        }
        if (this.listQuery.pageNum > 1) {
          setTimeout(()=>{
            let rowNum = this.listQuery.pageNum * this.listQuery.pageSize
            let toNumber = (rowNum / 2) * 48
            this.$refs.xTable.scrollTo(null, toNumber)
          }, 50)
        } else {
          this.$refs.xTable.clearScroll()
        }
      })
    },

    findWarehouseSpaceList(){
      //const params = {'warehouseCode': this.listQuery.warehouseCode}
      getWarehouseSpace(this.listQuery.warehouseCode).then((response)=>{
        this.warehouseSpaceList = response.data;
      })
    },
    // 添加移位单明细
    funcSubmit() {
      // if(!this.one)return this.$message.error('请输入大于0的数')
      // if(!this.two)return this.$message.error('小数点后保留六位小数，不能为负')
      // if(!this.three)return this.$message.error('移出数量不能大于可用数量')
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      let len = selectRecords.length
      for(let i = 0; i < len; i++){
        let moveQuantity = Number(selectRecords[i].moveQuantity)
        if(!moveQuantity||moveQuantity<0){
          this.$message.error('请输入大于0的数')
          return
        }
        let reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/
        if(!reg.test(moveQuantity)){
          this.$message.error('小数点后保留六位小数，不能为负')
          return
        }
        let canUseQuantity = Math.round((Number(selectRecords[i].quantity)-Number(selectRecords[i].useQuantity))*1000)/1000
        if(moveQuantity>canUseQuantity){
          this.$message.error('移出数量不能大于可用数量')
          return
        }
      }
      // this.getDifferentMap();
      this.$emit('fatherAddItem', selectRecords);

    },

    fucCancel() {
      this.$emit("fatherCancel");
    },

    formatterIsLock({cellValue}){
      const isLockStaus = ['否', '是']
      return isLockStaus[cellValue]
    },
     // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },

    // 手动勾选事件
    selectionChange({selection, row, checked}){
      for(let record of selection){
     /*   this.checkedRecords.filter(item=>{
          if(item.code == )
        })*/
      }
      this.updateCheckedRecords(checked, row);

    },
    // 全部勾选事件
    selectAll({selection, row, checked}){
      for(let record of selection){
        this.updateCheckedRecords(checked, record);
      }
    },


    updateCheckedRecords(checked, row){
      if(checked){
        if(!this.checkedRecordsMap.has(row.code)){
          this.checkedRecordsMap.set(row.code, row);
        }
      }else{
        if(this.checkedRecordsMap.has(row.code)){
          this.checkedRecordsMap.delete(row.code);
        }
      }
    },

    initCheckedRecordsMap(initRecords){
      if(initRecords != undefined && initRecords.length>0){

        for(let i=0;i<initRecords.length;i++){
          this.checkedRecordsMap.set(initRecords[i].inventoryCode, initRecords[i]);
          this.oldRecordsMap.set(initRecords[i].inventoryCode, initRecords[i]);
        }

      }
    },

    // 可用库存数量 = 库存数量 - 占用数量
    formatterCanUseQuantity({ cellValue, row }) {
      return row.quantity - row.useQuantity;
    },
    changeDate(value, prefix) {
      // 处理时间范围 start-end
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },

  },


};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
